const jpress = require('../../utils/jpress.js')
var Auth = require('../../utils/auth.js');
var util = require('../../utils/util.js');
var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
let isFocusing = false

import { ModalView } from '../../templates/modal-view/modal-view.js'
import Poster from '../../templates/components/wxa-plugin-canvas-poster/poster/poster';

Page({
    data: {
        title: '文章内容',
        article: null,
        detail: {},
        commentsList: [],
        ChildrenCommentsList: [],
        commentCount: '',
        detailDate: '',
        commentValue: '',
        wxParseData: {},
        display: 'none',
        showError:'none',
        page: 1,
        isLastPage: false,
        parentID: "0",
        focus: false,
        placeholder: "评论...",
        postID: null,
        scrollHeight: 0,
        postList: [],
        link: '',
        dialog: {
            title: '',
            content: '',
            hidden: true
        },
        reContent: '',
        isShow: false,//控制menubox是否显示
        isLoad: true,//解决menubox执行一次  
        menuBackgroup: false,
        likeImag: "like.png",
        likeList: [],
        likeCount: 0,
        displayLike: 'none',
        replayTemplateId: jpress.config.replayTemplateId,
        userid: "",
        toFromId: "",
        commentdate: "",
        flag: 1,
        logo: jpress.config.logo,
        enableComment: 'false',
        isLoading:false,
        total_comments:0,        
        isLoginPopup:false,
        openId:"",
        userInfo:{},
        system:'',
        downloadFileDomain:jpress.config.downloadFileDomain
    },
    onLoad: function (options) {
        var self = this;
        /** 是否开启评论 **/
        self.getEnableComment();
        /** 获取文章内容 **/
        self.fetchDetailData(options.id);
        /** 获取文章评论 **/
        self.fetchCommentData(options.id);

        wx.getSystemInfo({
            success: function (t) {
                var system = t.system.indexOf('iOS') != -1 ? 'iOS' : 'Android';
                self.setData({
                    system: system
                });
            }
        })
        Auth.setUserInfoData(self);
        Auth.checkLogin(self);
        self.showLikeImg(options.id);
        new ModalView;
    },

    /** 显示点赞图片 **/
    showLikeImg: function (articleId) {
        var self = this;
        var likes = [];
        jpress.getArticleLikes({
            articleId: articleId
        }).then(data => {
            if(data.users){
                for (var i = 0; i < data.users.length; i++) {
                    var avatarurl = "../../images/gravatar.png";
                    if (data.users[i].avatar.indexOf('wx.qlogo.cn') != -1) {
                        avatarurl = data.users[i].avatar;
                    }
                    likes[i] = avatarurl;
                }
                self.setData({
                    likeList: likes,
                    likeCount: likes.length
                });
            }
        })
    },
    /** 上拉触底事件 **/
    onReachBottom: function () { 
        var self = this;
        if (!self.data.isLastPage) {            
            self.fetchCommentData();
        }else{
            console.log('评论已经是最后一页了');
        }
    },
    // TODO
    /** 用户点击右上角转发 **/
    onShareAppMessage: function (res) {
        this.ShowHideMenu();
        console.log(res);
        return {
            title: '分享"' + app.getWebsiteName + '"的文章：' + this.data.detail.title.rendered,
            path: 'pages/detail/detail?id=' + this.data.detail.id,
            imageUrl: this.data.detail.post_thumbnail_image,
            success: function (res) {
                // 转发成功
                console.log(res);
            },
            fail: function (res) {
                console.log(res);
                // 转发失败
            }
        }
    },
    // TODO
    /** 阅读原文 **/
    gotowebpage: function () {
        var self = this;
        self.ShowHideMenu();
        var minAppType = jpress.config.minAppType;
        if (minAppType == "0") {
            wx.navigateTo({
                url: '../webpage/webpage?url=https://f.wsxxg.cn' + self.data.article.url
            })
        }else {
            self.copyLink(self.data.link);
        }
    },
    copyLink: function (url) {
        //this.ShowHideMenu();
        wx.setClipboardData({
            data: url,
            success: function (res) {
                wx.getClipboardData({
                    success: function (res) {
                        wx.showToast({
                            title: '链接已复制',
                            image: '../../images/link.png',
                            duration: 2000
                        })
                    }
                })
            }
        })
    },
    // TODO
    /** 点赞 **/
    clickLike: function (e) {
        var id = e.target.id;
        var self = this;
        if (id == 'likebottom') {
            this.ShowHideMenu();
        }
        if (self.data.openId) {
            jpress.likeArticle({
                openId: self.data.openId,
                articleId: self.data.article.id
            }).then(data => {
                if (data.status == '200') {
                    var _likeList = []
                    var _like = self.data.userInfo.avatarUrl;
                    _likeList.push(_like);
                    var tempLikeList = _likeList.concat(self.data.likeList);
                    var _likeCount = parseInt(self.data.likeCount) + 1;
                    self.setData({
                        likeList: tempLikeList,
                        likeCount: _likeCount,
                        displayLike: 'block'
                    });
                    wx.showToast({
                        title: '谢谢点赞',
                        icon: 'success',
                        duration: 900,
                        success: function () {
                        }
                    })
                }else if (data.status == '501') {
                    console.log(data.message);
                    wx.showToast({
                        title: '谢谢，已赞过',
                        icon: 'success',
                        duration: 900,
                        success: function () {
                        }
                    })
                }else {
                    console.log(response.data.message);
                }
                self.setData({
                    likeImag: "like-on.png"
                });
            })
        }else {
            Auth.checkSession(self);
        }
    },
    //TODO
    /** 判断当前用户是否点赞 **/
    getIslike: function () {
        var self = this;
        if (self.data.openId) {
            var data = {
                openId: self.data.openId,
                postid: self.data.postID
            };
            var url = Api.postIsLikeUrl();
            var postIsLikeRequest = wxRequest.postRequest(url, data);
            postIsLikeRequest
                .then(response => {
                    if (response.data.status == '200') {
                        self.setData({
                            likeImag: "like-on.png"
                        });

                        console.log("已赞过");
                    }

                })

        }
    },
    /** 返回首页 **/
    goHome: function () {
        wx.switchTab({
            url: '../index/index'
        })
    },
    //TODO
    /** 赞赏 **/
    praise: function () {
        this.ShowHideMenu();
        var self = this;
        var minAppType = jpress.config.minAppType;
        var system  =self.data.system;
        if (minAppType == "0" && system=='Android') {
            if (self.data.openId) {

                wx.navigateTo({
                    url: '../pay/pay?flag=1&openId=' + self.data.openId + '&articleId=' + self.data.article.id
                })
            }
            else {
                Auth.checkSession(self);
            }
        }
        else {
            var src = jpress.config.zanImageURL;
            wx.previewImage({
                urls: [src],
            });

        }
    },

    /** 获取是否开启评论设置 **/
    getEnableComment: function () {
        jpress.getEnableComment().then(data => {
            if(data.value){
                this.setData({
                    enableComment: data.value
                })
            }
        })

    },
    /** 获取文章内容 **/
    fetchDetailData: function (id) {
        var self = this;
        jpress.getArticle(id).then(data => {
            if(data.article){
                WxParse.wxParse('content', 'html', data.article.content, self, 5);
                data.article.created = util.cutstr(data.article.created, 10, 1);
                this.setData({
                    article: data.article,
                    display: "block",
                    displayLike: "block",
                })
                wx.setNavigationBarTitle({
                    title: data.article.title
                });
                this.getArticleRelevantList(id,5);

            // 调用API从本地缓存中获取阅读记录并记录
            var logs = wx.getStorageSync('readLogs') || [];
            // 过滤重复值
            if (logs.length > 0) {
                logs = logs.filter(function (log) {
                    return log[0] !== id;
                });
            }
            // 如果超过指定数量
            if (logs.length > 19) {
                logs.pop();//去除最后一个
            }
            logs.unshift([id, data.article.title]);
            wx.setStorageSync('readLogs', logs);

            }else {
                this.setData({
                    showError:"block",
                    display:"none",
                    errMessage:"网络连接错误"
                })
            }

        });
    },

    /** 获取相关内容 **/
    getArticleRelevantList: function (id,count) {
        jpress.getArticleRelevantList({
            articleId: id,
            count: count,
        }).then(data =>{
            if(data.articles){
                this.setData({
                    postList: data.articles
                })
            }
        })
    },


    //给a标签添加跳转和复制链接事件
    wxParseTagATap: function (e) {

    },
    /** 获取评论 **/
    fetchCommentData: function (id) {
        jpress.getCommentPage({
            articleId: id,
            page: this.data.page,
        }).then(data=>{
            if(data.page ){
                this.setData({
                    commentsList : this.data.commentsList.concat(data.page.list),
                    page: this.data.page+1,
                    isLastPage : data.page.lastPage,
                })
            }
        })
    },
    /** 显示或隐藏功能菜单 **/
    ShowHideMenu: function () {
        this.setData({
            isShow: !this.data.isShow,
            isLoad: false,
            menuBackgroup: !this.data.false
        })
    },
    /** 点击非评论区隐藏功能菜单 **/
    hiddenMenubox: function () {
        this.setData({
            isShow: false,
            menuBackgroup: false
        })
    },

    /** 底部刷新 **/
    loadMore: function (e) {
        var self = this;
        if (!self.data.isLastPage) {
            this.fetchCommentData();
        }
        else {
            wx.showToast({
                title: '没有更多内容',
                mask: false,
                duration: 1000
            });
        }
    },

    /** 回复 **/
    replay: function (e) {
        var self = this;
        var id = e.target.dataset.id;
        var name = e.target.dataset.name;
        isFocusing = true;
        console.log("回复名称")
        if (self.data.enableComment){
            self.setData({
                parentID: id,
                placeholder: "回复" + name + ":",
                focus: true,
            });
        }
    },
    onReplyBlur: function (e) {
        var self = this;
       // console.log('onReplyBlur', isFocusing);
        if (!isFocusing) {
            {
                const text = e.detail.value.trim();
                if (text === '') {
                    self.setData({
                        parentID: "0",
                        placeholder: "评论...",
                        userid: "",
                        toFromId: "",
                        commentdate: ""
                    });
                }

            }
        }
       // console.log(isFocusing);
    },
    onRepleyFocus: function (e) {
        var self = this;
        isFocusing = false;
        //console.log('onRepleyFocus', isFocusing);
        if (!self.data.focus) {
            self.setData({ focus: true })
        }


    },
    /** 提交评论 **/
    formSubmit: function (e) {
        var self = this;
        var comment = e.detail.value.inputComment;
        var parent = self.data.parentID;
        var postID = e.detail.value.inputPostID;
        if (comment.length === 0) {
            self.setData({
                'dialog.hidden': false,
                'dialog.title': '提示',
                'dialog.content': '没有填写评论内容。'

            });
        }
        jpress.doPostComment({
            articleId: postID,
            pid: parent
        },comment).then(data=>{
            if(data.comment){
                this.refreshCommentsListData(parent,data.comment,self.data.commentsList);
            }
        },e => {
            wx.showToast({
                title: e.message,
                icon: 'clear',
                duration: 900,
            })
        })
        console.log("提交评论")
    },
    /** 同意获取用户信息 **/
    agreeGetUser:function(e){
        console.log("用户同意获取信息。。。。")
        var userInfo = e.detail.userInfo;
        var self = this;
        if (userInfo){
            Auth.checkAgreeGetUser(e,app,self);
            self.setData({ userInfo: userInfo});
        }
        setTimeout(function () {
            self.setData({ isLoginPopup: false })
        }, 1200);
    },
    /** 关闭登录弹出 **/
    closeLoginPopup:function(){
        this.setData({ isLoginPopup: false });
    },
    /** 打开登录弹出 **/
    openLoginPopup:function(){
        this.setData({ isLoginPopup: true });
    },
    confirm: function () {
        this.setData({
            'dialog.hidden': true,
            'dialog.title': '',
            'dialog.content': ''
        })
    },    
    downimageTolocal: function () {
        var imageInlocalFlag = false;

    },
    //将canvas转换为图片保存到本地，然后将路径传给image图片的src
    createPosterLocal: function (postImageLocal, qrcodeLoal, title, excerpt) {
        var that = this;
        wx.showLoading({
            title: "正在生成海报",
            mask: true,
        });
        var context = wx.createCanvasContext('mycanvas');
        context.setFillStyle('#ffffff');//填充背景色
        context.fillRect(0, 0, 600, 970);
        context.drawImage(postImageLocal, 0, 0, 600, 400);//绘制首图
        context.drawImage(qrcodeLoal, 90, 720, 180, 180);//绘制二维码
        context.drawImage(that.data.logo, 350, 740, 130, 130);//画logo
        //const grd = context.createLinearGradient(30, 690, 570, 690)//定义一个线性渐变的颜色
        //grd.addColorStop(0, 'black')
        //grd.addColorStop(1, '#118fff')
        //context.setFillStyle(grd)
        context.setFillStyle("#000000");
        context.setFontSize(20);
        context.setTextAlign('center');
        context.fillText("阅读文章,请长按识别二维码", 300, 940);
        //context.setStrokeStyle(grd)
        context.setFillStyle("#000000");
        context.beginPath()//分割线
        context.moveTo(30, 690)
        context.lineTo(570, 690)
        context.stroke();
        // this.setUserInfo(context);//用户信息
        util.drawTitleExcerpt(context, title, excerpt);//文章标题
        context.draw();
        //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
        setTimeout(function () {
            wx.canvasToTempFilePath({
                canvasId: 'mycanvas',
                success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    // that.setData({
                    //     imagePath: tempFilePath,
                    //     maskHidden: "none"
                    // });
                    wx.hideLoading();
                    console.log("海报图片路径：" + res.tempFilePath);
                    that.modalView.showModal({
                        title: '保存至相册可以分享到朋友圈',
                        confirmation: false,
                        confirmationText: '',
                        inputFields: [{
                            fieldName: 'posterImage',
                            fieldType: 'Image',
                            fieldPlaceHolder: '',
                            fieldDatasource: res.tempFilePath,
                            isRequired: false,
                        }],
                        confirm: function (res) {
                            console.log(res)
                            //用户按确定按钮以后会回到这里，并且对输入的表单数据会带回
                        }
                    })


                },
                fail: function (res) {
                    console.log(res);
                }
            });
        }, 900)
    },
    onPosterSuccess(e) {
        const { detail } = e;        
        this.showModal(detail);
      },
      onPosterFail(err) {  
        wx.showToast({
            title: err,
            mask: true,
            duration: 2000
        });
      },

    onCreatePoster:function() {      
        var self = this;    
        this.ShowHideMenu();     
        if (self.data.openId) {
            self.createArticlePoster(self,util,self.modalView,Poster);
        }
        else {
            Auth.checkSession(self);

        }
        
    },

    showModal:function(posterPath){
        this.modalView.showModal({
                    title: '保存至相册可以分享给好友',
                    confirmation: false,
                    confirmationText: '',
                    inputFields: [{
                        fieldName: 'posterImage',
                        fieldType: 'Image',
                        fieldPlaceHolder: '',
                        fieldDatasource: posterPath,
                        isRequired: false,
                    }],
                    confirm: function (res) {
                        console.log(res)
                              }
                })
    },
    
    createArticlePoster:function(appPage, util, modalView,poster){
        var postImageUrl = "";
        var posterImagePath = "";
        var fristImage = appPage.data.article.firstImage;

        //获取文章首图临时地址，若没有就用默认的图片,如果图片不是request域名，使用本地图片
        if (fristImage) {
            var n = 0;
            for (var i = 0; i < jpress.config.downloadFileDomain.length;i++){
                if(fristImage.indexOf(jpress.config.downloadFileDomain[i].domain) != -1){
                    n++;
                    break;
                }
            }
            if(n>0){
                postImageUrl = fristImage;
            }else{
                postImageUrl = jpress.config.postImageUrl;
                posterImagePath = postImageUrl;
            }
        }else {
            postImageUrl = jpress.config.postImageUrl;
            posterImagePath = postImageUrl;
        }

        var postId = appPage.data.article.id;
        var title = appPage.data.article.title;
        var path = "pages/detail/detail?id=" + postId;
        jpress.getWinxinQrcodeImg({
            articleId:postId,
            path: path,
            openId: appPage.data.openId
        }).then(data =>{
            var posterQrcodeUrl = jpress.config.host + data.url;
            const downloadTaskQrcodeImage = wx.downloadFile({
                url: posterQrcodeUrl,
                success: res => {
                if (res.statusCode === 200) {
                var qrcodeImagePath = res.tempFilePath;
                console.log("二维码图片本地位置：" + res.tempFilePath);
                    const downloadTaskForPostImage = wx.downloadFile({
                        url: postImageUrl,
                        success: res => {
                        if (res.statusCode === 200){
                            posterImagePath = res.tempFilePath;
                            console.log("文章图片本地位置：" + res.tempFilePath);
                            if (posterImagePath && qrcodeImagePath) {
                                appPage.createPosterLocal(posterImagePath, qrcodeImagePath, title, util.removeHTML(appPage.data.article.content));
                            }
                        }else {
                            console.log(res);
                            wx.hideLoading();
                            wx.showToast({
                                title: "生成海报失败...",
                                mask: true,
                                duration: 2000
                            });
                            return false;


                        }
                    }
                });
                    downloadTaskForPostImage.onProgressUpdate((res) => {
                        console.log('下载文章图片进度：' + res.progress)

                })
            }
        else {
                console.log(res);
                //wx.hideLoading();
                flag = false;
                wx.showToast({
                    title: "生成海报失败...",
                    mask: true,
                    duration: 2000
                });
                return false;
            }
        }
        });
        })
    },

    // 刷新评论
    refreshCommentsListData: function (parentId, comment,commentsList) {

        if(parentId == '0'){
            commentsList.unshift(comment);
            this.setData({
                reContent: '',
                commentsList: commentsList
            })
        }else {
            var newCommentsList = this.reloadCommentsListData(parentId, comment, commentsList);
            this.setData({
                reContent: '',
                commentsList: commentsList
            })
        }
    },
    // 重新加载频率数据
    reloadCommentsListData: function (parentId,comment,commentsList) {
        var newCommentsList = [];
        for (var i = 0; i < commentsList.length; i++) {
            console.log("commentId:" + commentsList[i].id)
            if (commentsList[i].id == parentId) {
                commentsList[i].child.push(comment);
            }else {
                console.log("child:" + commentsList[i].id)
                this.reloadCommentsListData(parentId,comment,commentsList[i].child);
            }
            newCommentsList.push(commentsList[i]);
        }
        return newCommentsList;
    }

})